package service

import (
	"errors"
	"gin-demo/global"
	"gin-demo/model"
	"gin-demo/model/request"
	"gin-demo/model/response"
	"gin-demo/util"
	"github.com/gin-gonic/gin"
	uuid "github.com/satori/go.uuid"
)

// 用户注册
func Register(register request.Register) (err error) {
	username := register.Username
	password := register.Password
	u,_ := UserByName(username)
	if u.ID != 0 {
		return errors.New("用户已存在！")
	}
	salt := util.RandomString(5)
	// 创建用户
	newUser := model.User {
		UUID: uuid.NewV4(),
		Username: username,
		Password: util.MakePasswd(password, salt),
		Salt: salt,
		Avatar: "/uploads/default/logo.png",
	}
	err = global.GN_DB.Create(&newUser).Error

	return err
}

// 登录
func Login(login request.Login) (model.User, error) {
	// 获取参数
	username := login.Username
	password := login.Password
	user,err := UserByName(username)
	if err == nil {
		ret := util.ValidatePasswd(password, user.Salt, user.Password)
		if ret {
			return user, nil
		} else {
			return user, errors.New("密码错误！")
		}
	} else {
		return user,err
	}
}

// 根据手机号获得用户
func UserByMobile(mobile string) (model.User, error) {
	var user model.User
	err := global.GN_DB.Where("mobile = ?", mobile).First(&user).Error
	user.Avatar = util.TransformImageUrl(user.Avatar)

	return user,err
}

// 根据用户名获得用户
func UserByName(username string) (model.User, error) {
	var user model.User
	err := global.GN_DB.Where("username = ?", username).First(&user).Error
	user.Avatar = util.TransformImageUrl(user.Avatar)

	return user,err
}

// 获得用户信息
func UserInfo(userId uint64) (response.UserInfo, error) {
	user := model.User{}
	err := global.GN_DB.First(&user, userId).Error

	u := UserSimpleInfo(user)

	return u,err
}

// 获得用户信息
func UserInfoById(userId uint64) (model.User, error) {
	user := model.User{}
	err := global.GN_DB.First(&user, userId).Error

	return user,err
}

// 用户简单信息
func UserSimpleInfo(user model.User) response.UserInfo {
	user.Avatar = util.TransformImageUrl(user.Avatar)
	u := response.UserInfo{
		Id:       user.ID,
		UUID:     user.UUID,
		Username: user.Username,
		Nickname: user.Nickname,
		Avatar:   user.Avatar,
		Sex:      user.Sex,
		Online:   user.Online,
		Intro:    user.Intro,
	}

	return u
}

// 从Gin的Context中获取从jwt解析出来的用户ID
func GetUserID(ctx *gin.Context) uint64 {
	if claims, exists := ctx.Get("claims"); !exists {
		global.GN_LOG.Error("从Gin的Context中获取从jwt解析出来的用户ID失败, 请检查路由是否使用jwt中间件")
		return 0
	} else {
		waitUse := claims.(*request.LoginClaims)
		return waitUse.ID
	}
}

// 修改用户信息
func Modify(userModify request.UserModify, userId uint64) (err error) {
	user := model.User{
		Nickname: userModify.Nickname,
		Avatar:   userModify.Avatar,
		Sex:      userModify.Sex,
		Intro:    userModify.Intro,
	}
	picLen := len(user.Avatar)
	if picLen > 0 {
		hostLen := len(global.GN_CONFIG.System.ImgHost)
		user.Avatar = user.Avatar[hostLen:]
	}
	err = global.GN_DB.Where("id=?", userId).Updates(&user).Error

	return err
}